#!/bin/sh

### BEGIN INIT INFO
# Provides:          ripple
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the ripple network node
# Description:       starts chainsqld using start-stop-daemon
### END INIT INFO

set -e

NAME=chainsqld
USER="chainsqld"
GROUP="chainsqld"
PIDFILE=/var/run/$NAME.pid
DAEMON=/usr/local/sbin/chainsqld
DAEMON_OPTS="--conf /etc/ripple/chainsqld.cfg"
NET_OPTS="--net $DAEMON_OPTS"
LOGDIR="/var/log/chainsqld"
DBDIR="/var/db/chainsqld/db/hyperldb"

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

# I wish it didn't come down to this, but this is the easiest way to ensure
# sanity of an install.
if [ ! -d $LOGDIR ]; then
	mkdir -p $LOGDIR
	chown $USER:$GROUP $LOGDIR
fi
if [ ! -d $DBDIR ]; then
	mkdir -p $DBDIR
	chown -R $USER:$GROUP $DBDIR
fi

case "$1" in
    start)
        echo -n "Starting daemon: "$NAME
        start-stop-daemon --start --quiet --background -m --pidfile $PIDFILE \
            --exec $DAEMON --chuid $USER --group $GROUP --verbose -- $NET_OPTS
        echo "."
        ;;

    stop)
        echo -n "Stopping daemon: "$NAME
        $DAEMON $DAEMON_OPTS stop
        rm -f $PIDFILE
        echo "."
        ;;

    restart)
        echo -n "Restarting daemon: "$NAME
        $DAEMON $DAEMON_OPTS stop
        rm -f $PIDFILE
        start-stop-daemon --start --quiet --background -m --pidfile $PIDFILE \
            --exec $DAEMON --chuid $USER --group $GROUP -- $NET_OPTS
        echo "."
        ;;

    status)
        echo "Status of $NAME:"
        echo -n "PID of $NAME: "
        if [ -f "$PIDFILE" ]; then
                cat $PIDFILE
                $DAEMON $DAEMON_OPTS server_info
        else
                echo "$NAME not running."
        fi
        echo "."
        ;;

    fetch)
        echo "$NAME ledger fetching info:"
        $DAEMON $DAEMON_OPTS fetch_info
        echo "."
        ;;

    uptime)
        echo "$NAME uptime:"
        $DAEMON $DAEMON_OPTS get_counts
        echo "."
        ;;

    startconfig)
        echo "$NAME is being started with the following command line:"
        echo "$DAEMON $NET_OPTS"
        echo "."
        ;;

    command)
        # Truncate the script's argument vector by one position to get rid of
        # this entry.
        shift

        # Pass the remainder of the argument vector to chainsqld.
        $DAEMON $DAEMON_OPTS "$@"
        echo "."
        ;;

    test)
        $DAEMON $DAEMON_OPTS ping
        echo "."
        ;;

    *)
        echo "Usage: $0 {start|stop|restart|status|fetch|uptime|startconfig|"
        echo "           command|test}"
        exit 1
esac

exit 0

